//
//  NThemeTableViewController.m
//  News
//
//  Created by zhangtao on 2018/10/10.
//  Copyright © 2018年 zt.td. All rights reserved.
//

#import "NThemeTableViewController.h"
#import "NThemeCollectionViewCell.h"
#import "NItemSearchView.h"
#import "NThemeDetailViewController.h"

@interface NThemeTableViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,ThemeCancelOrFocusDelegate>
@property(nonatomic,strong)UICollectionView *collection;
@property(nonatomic,strong)NItemSearchView *seaerchView;

@property(nonatomic,strong)NSMutableArray <NSMutableArray<NTopicalModel *> *> *topicals;
@property(nonatomic,strong)NSMutableArray <NSNumber *> *cps; //当前页
@property(nonatomic,assign)NSInteger cpIndex; //热门类型下标
@end

@implementation NThemeTableViewController

static NSString * const reuseIdentifier = @"Cell";

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _topicals = [NSMutableArray arrayWithCapacity:0];
    _cps = [NSMutableArray arrayWithCapacity:0];
    _cpIndex = 0;
    for (int i = 0; i<3; i++) {
        NSMutableArray *arr = [NSMutableArray arrayWithCapacity:0];
        [_cps addObject:[NSNumber numberWithInt:1]];
        [_topicals addObject:arr];

    }
    
    [self.navigationItem setTitleView:self.seaerchView];
    self.view.backgroundColor = [UIColor whiteColor];
//    UICollectionViewFlowLayout
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    self.collection = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:layout];
    self.collection.backgroundColor = [UIColor whiteColor];
    self.collection.delegate = self;
    self.collection.dataSource = self;
    self.collection.scrollEnabled = YES;
    [self.view addSubview:self.collection];
    
    [self.collection registerNib:[UINib nibWithNibName:@"NThemeCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:reuseIdentifier];
    
    [self requestTopicalsWithUrl:HTTP_GET_HOT_TOPICALS];
    
}


-(NItemSearchView *)seaerchView{
    if (!_seaerchView) {
        _seaerchView = [[NItemSearchView alloc]initWithFrame:CGRectMake(10, 0, self.view.frame.size.width-20, 44) items:@[@"人气",@"最新",@"关注",@"我的主题"]];
        WEAKSELF;
        _seaerchView.ItemSearchViewCallBack = ^(NSInteger tag) {
            if (tag == -1) {
                
            }else if (tag == -2){
                
            }else if (tag == 0) {
                weakSelf.cpIndex = 0;
                if (weakSelf.topicals[0].count==0) {
                    NSString *url = HTTP_GET_HOT_TOPICALS;
                    [weakSelf requestTopicalsWithUrl:url];
                }else{
                    [weakSelf.collection reloadData];
                }
               
                
            }else if (tag == 1){
                weakSelf.cpIndex = 1;
                if (weakSelf.topicals[1].count==0) {
                    NSString *url = HTTP_GET_NEWS_TOPICALS;
                    [weakSelf requestTopicalsWithUrl:url];
                }else{
                    [weakSelf.collection reloadData];
                }
                
            }else if (tag == 2){
                weakSelf.cpIndex = 2;
                if (weakSelf.topicals[2].count==0) {
                    NSString *url = HTTP_GET_FOLLOW_TOPICALS;
                    [weakSelf requestTopicalsWithUrl:url];
                }else{
                    [weakSelf.collection reloadData];
                }
                
            }else if (tag == 3){
                //我的主题，用H5
            }
        };
    }
    return _seaerchView;
}

-(void)requestTopicalsWithUrl:(NSString *)url{
    NSDictionary *param;
    if ([url isEqualToString:HTTP_GET_FOLLOW_TOPICALS]) {
        
        param = @{@"cp":_cps[_cpIndex],@"cuid":CUID};

    }else{
        param = @{@"cp":_cps[_cpIndex]};
    }
    
    [[NHTTPManage shareInstance]afGet:url andParam:param success:^(id  _Nonnull responseObject) {
        
        for (NSDictionary *dic in responseObject[@"Data"]) {
            NTopicalModel *model = [[NTopicalModel alloc]initWithDic:dic];
            [self.topicals[self.cpIndex] addObject:model];
        }
        
        [self.collection reloadData];
        
    } failture:^(id  _Nonnull error) {
        
        NSLog(@"error");
        
    }];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _topicals[_cpIndex].count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    NThemeCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    cell.delegate = self;
    cell.model = self.topicals[_cpIndex][indexPath.item];
    return cell;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake((ACEWidth-40)/3, (ACEWidth-40)/3+80);
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(10, 10, 10, 10);
//    return UIEdgeInsetsZero;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NThemeDetailViewController *detail = [[NThemeDetailViewController alloc]init];
    detail.title = _topicals[_cpIndex][indexPath.item].TopicalName;
    detail.topicalModel = _topicals[_cpIndex][indexPath.item];
//    detail.topicalID = _topicals[_cpIndex][indexPath.item].ID;
    detail.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detail animated:YES];
}

//设置水平间距 (同一行的cell的左右间距）
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 10;
}
//垂直间距 (同一列cell上下间距)
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 10;
}


/**
 取消或关注

 @param model 取消或关注对象
 @param isCancel yes == 取消 no==关注
 @param cell 对应的cell
 */
-(void)themeCancelOrfocusModel:(NTopicalModel *)model cancel:(BOOL)isCancel cell:(nonnull UICollectionViewCell *)cell{
//    NThemeCollectionViewCell *cel = (NThemeCollectionViewCell *)cell;
    NSString *url = isCancel==YES?HTTP_FOLLOW_TOPICAL:HTTP_CANCEL_TOPICAL;
    NSDictionary *param = @{@"token":TOKEN,@"cuid":CUID,@"tid":[NSString stringWithFormat:@"%@",model.ID]};
    [[NHTTPManage shareInstance]afPOST:url andParam:param success:^(id  _Nonnull responseObject) {
        NSLog(@"%@",responseObject);
        
        ((NThemeCollectionViewCell *)cell).focusBtn.selected = isCancel;
        NSString *str = [NSString stringWithFormat:@"%@成功",isCancel==YES?@"关注":@"取消"];
        [ACEPublicTool showToastInWindow:str];
        NOnlineFocusModel *onleModel = [NOnlineFocusModel sharedInstance];
        if (isCancel == YES) {
            [onleModel addfouce:model.ID name:model.TopicalName];
        }else{
            [onleModel deleteFouceId:model.ID];
        }
//        [self updateTopicsArrayWithID:model.ID state:isCancel];

    } failture:^(id  _Nonnull error) {
        NSLog(@"..");
        [ACEPublicTool showToastInWindow:error];
    }];
}

-(void)updateTopicsArrayWithID:(NSNumber *)ID state:(BOOL)state{
    for (NSMutableArray *arr in _topicals) {
        if (arr.count>0) {
            for (NTopicalModel *model in arr) {
                if (model.ID == ID) {
                    
                }
            }
        }
    }
}

#pragma mark <UICollectionViewDelegate>

/*
// Uncomment this method to specify if the specified item should be highlighted during tracking
- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath {
	return YES;
}
*/

/*
// Uncomment this method to specify if the specified item should be selected
- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
*/

/*
// Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
- (BOOL)collectionView:(UICollectionView *)collectionView shouldShowMenuForItemAtIndexPath:(NSIndexPath *)indexPath {
	return NO;
}

- (BOOL)collectionView:(UICollectionView *)collectionView canPerformAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
	return NO;
}

- (void)collectionView:(UICollectionView *)collectionView performAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
	
}
*/

@end
